#ifndef RTSPTHREAD_H
#define RTSPTHREAD_H

#include <QObject>
#include <QThread>

extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/mathematics.h"
#include "libavutil/time.h"
#include "libswscale/swscale.h"
#include "libavutil/audio_fifo.h"
#include "libswresample/swresample.h"
}
#include "videodecoderthread.h"
class RtspThread : public QThread
{
    Q_OBJECT
public:
    explicit RtspThread(QObject *parent = nullptr);
    void setUrl(QString strUrl);
    void setRecording(bool bRecord);

    void quit();
protected:
    void run();
    AVCodecContext *openDecoder( AVCodecParameters *codecpar,AVPixelFormat & fmt);
    //录制相关函数
    AVStream *AddVideoStream(AVFormatContext* oc,AVCodecContext** pOutCodecCtx,AVFormatContext* ic,int index,bool mark,bool open,int nW,int nH);
    AVStream *AddAudioStream(AVFormatContext* oc,AVCodecContext** pOutCodecCtx,AVFormatContext* ic,int index,bool mark,bool open);
    int InitConvertedSamples(uint8_t ***converted_input_samples,AVCodecContext *output_codec_context,int frame_size);
    int ConvertSamples(const uint8_t **input_data,uint8_t **converted_data, const int frame_size,SwrContext *resample_context);
    int AddSamplesToFifo(AVAudioFifo *fifo,uint8_t **converted_input_samples,const int frame_size);
    int AudioResampler(AVCodecContext *input_codec_context,AVCodecContext *output_codec_context,AVFrame *input_frame,AVAudioFifo *fifo_buffer);
    int InitOutputFrame(AVFrame **frame,AVCodecContext *output_codec_context,int frame_size);
    int EncodeAudioFrameRtsp(AVFrame *frame,AVFormatContext *oc,AVStream *audio_st,AVCodecContext *out_codec_ctx,int index,AVFormatContext *ic);
    int LoadEncodeAndWrite(AVAudioFifo *fifo,AVFormatContext *oc,AVStream *audio_st,AVCodecContext *out_codec_ctx,int index,AVFormatContext *ic, int &pts);

signals:
    void connecting();
    void connectFail();
    void connectSucc();
    void recordEnd(QString strFile);
    void updateFrame(QImage *img);
private:

    QString m_strUrl;
    bool m_bRecording;
    bool m_bRun = true;
};

#endif // RTSPTHREAD_H
